<?php
/**
 * 图片上传
 *
 * @author Administrator
 *
 */
namespace App\Http\Controllers;

define('DS', DIRECTORY_SEPARATOR);
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use \DB;

class UploadController extends CommonController
{

    /**
     * 显示首页。
     *
     * @return Response
     */
    public function getIndex()
    {
        echo "aa";
    }

    public function postIndex(Request $request)
    {
        //定义好哪些文件允许上传,同时为文件夹名做准备
        $ext_arr = array(
            'image' => array(
                'gif',
                'jpg',
                'jpeg',
                'png',
                'bmp'
            ),
            'flash' => array(
                'swf',
                'flv'
            ),
            'media' => array(
                'swf',
                'flv',
                'mp3',
                'wav',
                'wma',
                'wmv',
                'mid',
                'avi',
                'mpg',
                'asf',
                'rm',
                'rmvb'
            ),
            'file'  => array(
                'doc',
                'docx',
                'xls',
                'xlsx',
                'ppt',
                'htm',
                'html',
                'txt',
                'zip',
                'rar',
                'gz',
                'pdf',
                'bz2'
            )
        );

        if ($request->hasFile('myfile')) {
            //PHP上传失败
            if (!empty($_FILES['myfile']['error'])) {
                switch ($_FILES['myfile']['error']) {
                    case '1':
                        $error = '超过php.ini允许的大小。';
                        break;
                    case '2':
                        $error = '超过表单允许的大小。';
                        break;
                    case '3':
                        $error = '图片只有部分被上传。';
                        break;
                    case '4':
                        $error = '请选择图片。';
                        break;
                    case '6':
                        $error = '找不到临时目录。';
                        break;
                    case '7':
                        $error = '写文件到硬盘出错。';
                        break;
                    case '8':
                        $error = 'File upload stopped by extension。';
                        break;
                    case '999':
                    default:
                        $error = '未知错误。';
                }
                $this->alert($error);
            }
            //文件大小
            $file_size = $_FILES['myfile']['size'];
            //检查文件名
            if (!$_FILES['myfile']['name']) {
                $this->alert("请选择文件。");
            }
            $file = $request->file('myfile');

            $php_path = dirname(__FILE__) . DS;
            $php_url = "";
            //文件保存目录路径
            $save_path = config('upload.uploadDir');
            //文件保存目录URL
            $save_url = $php_url . '/public' . '/attached/';

            //最大文件大小
            $max_size = 500000000;

            //获取绝对路径
            $save_path = realpath($save_path) . DS;

            //获取扩展名
            $file_ext = $file->getClientOriginalExtension();
            //判断是否允许上传
            $isAllow = false;
            foreach ($ext_arr as $key => $val) {
                if (in_array($file_ext, $val)) {
                    $isAllow = true;
                    $dir_name = $key;
                    break;
                }
            }
            if (!$isAllow) {
                $this->alert("上传文件扩展名是不允许的扩展名。");
            }

            //创建类型文件夹
            if ($dir_name !== '') {
                $save_path .= $dir_name . "/";
                $save_url .= $dir_name . "/";
                if (!file_exists($save_path)) {
                    mkdir($save_path);
                    mkdir($save_path . "_large");
                    mkdir($save_path . "_thumb");
                }
            }
            //创建日期文件夹
            $ymd = date("Ymd");
            $save_path .= $ymd . "/";
            $save_url .= $ymd . "/";
            if (!file_exists($save_path)) {
                mkdir($save_path);
                mkdir($save_path . "_large");
                mkdir($save_path . "_thumb");
            }
            //新文件名
            $new_file = date("YmdHis") . '_' . rand(10000, 99999);
            $new_file_name = $new_file . "." . $file_ext;
            //移动文件
            $file_path = $save_path . $new_file_name;
            //检查目录
            if (@is_dir($save_path) === false) {
                $this->alert("上传目录不存在。");
            }
            //检查目录写权限
            if (@is_writable($save_path) === false) {
                $this->alert("上传目录没有写权限。");
            }
            $tmp_name = $file->getPathname();
            //检查是否已上传 检查文件是不是通过post方法上传的文件 隔离攻击
            if (@is_uploaded_file($tmp_name) === false) {
                $this->alert("临时文件可能不是上传文件。");
            }
            //检查文件大小
            if ($file_size > $max_size) {
                $this->alert("上传文件大小超过限制。");
            }
            if (move_uploaded_file($tmp_name, $file_path) === false) {
                $this->alert("上传文件失败。");
            }
            $file_url = $save_url . $new_file_name;

            //如果是图片则生成大图和小图
            if ('image' == $dir_name) {
                //生成大图小图
                //大
                $imageInfo = getimagesize($file_path);
                $lh = $imageInfo[1] / ($imageInfo[0] / 358);
                $large_url = $save_path . "_large/" . $new_file_name;
                $this->img_create_small($file_path, 358, $lh, $large_url);
                //小
                $th = $imageInfo[1] / ($imageInfo[0] / 158);
                $thumb_url = $save_path . "_thumb/" . $new_file_name;
                $this->img_create_small($file_path, 158, $th, $thumb_url);
            }

            header('Content-type: text/html; charset=UTF-8');
            echo json_encode(
                array(
                    'error'    => 0,
                    'url'      => str_replace('/public/', '', $file_url),
                    'path'     => $this->wjtrUrl . str_replace('/public/', '', $file_url),
                    'filename'     => $_FILES['myfile']['name'],
                    'filetype'     => $file_ext,
                    'filesize' => $file_size,
                )
            );
            exit();
        }else{
        	$this->alert("上传失败");
        }
    }

    private function alert($msg)
    {

        header('Content-type: text/html; charset=UTF-8');
        echo json_encode(
            array(
                'error'   => 1,
                'message' => $msg
            )
        );
        exit();
    }

    static function img_create_small($big_img, $width, $height, $small_img)
    { // 原始大图地址，缩略图宽度，高度，缩略图地址
        $imgage = getimagesize($big_img); // 得到原始大图片
        switch ($imgage[2]) { // 图像类型判断
            case 1:
                $im = imagecreatefromgif($big_img);
                break;
            case 2:
                $im = imagecreatefromjpeg($big_img);
                break;
            case 3:
                $im = imagecreatefrompng($big_img);
                break;
        }
        $src_W = $imgage[0]; // 获取大图片宽度
        $src_H = $imgage[1]; // 获取大图片高度
        $tn = imagecreatetruecolor($width, $height); // 创建缩略图
        imagecopyresampled($tn, $im, 0, 0, 0, 0, $width, $height, $src_W, $src_H); // 复制图像并改变大小
        imagejpeg($tn, $small_img); // 输出图像
    }
}